package com.example.saifly.inPagePlan.cureMethod.fragment;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.common.Fragment;
import com.example.common.Retrofit.RetrofitHelper;
import com.example.saifly.R;
import com.example.saifly.inPageMy.Artical;
import com.example.saifly.inPagePlan.article.ArticleDetailActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

/**
 * @Author:ShengyiJi
 * @Description:饮食健康子页面
 * @Date:
 */
public class EatingHealthFragment extends Fragment {

    private RecyclerView rvEatingHealth;
    private List<Item> itemList;

    private MyAdapter myAdapter;

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_in_curemethod_eating_health;
    }

    @Override
    protected void init() {
        super.init();

        rvEatingHealth = getActivity().findViewById(R.id.eating_health_rv);
        itemList=new ArrayList<>();

        //第一步 设置LayoutManager 布局管理器
        RecyclerView.LayoutManager layoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
        rvEatingHealth.setLayoutManager(layoutManager);

        //第二步设置Adapter 适配器
        myAdapter = new MyAdapter();
        rvEatingHealth.setAdapter(myAdapter);

        new Thread(new Runnable() {
            @Override
            public void run()
            {
                eatingHealthArticle(2);
            }
        }).start();

    }

    private interface getArticle {
        @Headers({"Content-Type:application/json"})
        @POST("/manage/getArticle")
        Call<ResponseBody> eatingHealthArticle(@Body JSONObject jsonObject);
    }

    private void eatingHealthArticle(int articleType) {
        RetrofitHelper retrofitHelper = new RetrofitHelper();
        Retrofit retrofit = retrofitHelper.getRetrofit();

        getArticle apiEatingHealth = retrofit.create(getArticle.class);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("articleType", articleType);
        Log.d("啦啦啦啦", "eatingHealthArticle: "+jsonObject);

        Call<ResponseBody> call = apiEatingHealth.eatingHealthArticle(jsonObject);
        final Response<ResponseBody> response;
        try {
            response = call.execute();
            String jsonResult=response.body().string();
            Log.d("啦啦啦啦", "logData: "+jsonResult);
            JSONObject result = JSON.parseObject(jsonResult);

            if (result.getInteger("code") == 1) {
                //获取的code为1 说明请求成功
                List<Artical>articals=JSON.parseArray(result.getString("result"),Artical.class);

                for(int i=0;i<articals.size();i++)
                {
                    String articleTitle=articals.get(i).getTitle();   //获取文章标题
                    String articleContent=articals.get(i).getLink();    //获取文章内容
                    String articleID=articals.get(i).getArticalId();    //获取文章ID
                    Item item = new Item("123", articleTitle,articleContent,articleID);
                    itemList.add(item);
                }

                getActivity().runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        myAdapter.replaceData(itemList);
                        myAdapter.notifyDataSetChanged();
                    }
                });

            } else {
                //请求失败
                getActivity().runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        Toast toast=Toast.makeText(getActivity().getApplicationContext(), "获取收藏失败，请重新尝试", Toast.LENGTH_LONG);
                        showMyToast(toast,10*500);// 设置显示时间  一次10ms,显示500次，即显示5s
                    }
                });
            }
        } catch (Exception e) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getActivity(), "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
    }

    //Toast 自定义显示时长
    public void showMyToast(final Toast toast, final int cnt) {
        final Timer timer =new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                toast.show();
            }
        },0,3000);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                toast.cancel();
                timer.cancel();
            }
        }, cnt );
    }

    private class Item {
        String imageUrl;
        String title;
        String content;
        String ID;

        public Item(String imageUrl, String title,String content,String ID) {
            this.imageUrl = imageUrl;
            this.title = title;
            this.content=content;
            this.ID=ID;
        }
    }

    private class MyAdapter extends BaseQuickAdapter<Item, BaseViewHolder> {
        public MyAdapter() {
            super(R.layout.holder_collection_rv, itemList);
        }

        @Override
        protected void convert(@NonNull BaseViewHolder holder,Item item) {
            int position = holder.getLayoutPosition();

            Glide.with(EatingHealthFragment.this).load(R.drawable.ic_collection_passageimage).into((ImageView) holder.getView(R.id.holder_collection_imageUrl));
            holder.setText(R.id.holder_collection_title, itemList.get(position).title);

            holder.addOnClickListener(R.id.eating_health_rv);
            holder.addOnClickListener(R.id.holder_article);

            setOnItemChildClickListener(new OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    if (view.getId()==R.id.holder_article)
                    {
                        String content=itemList.get(position).content;
                        String articleID=itemList.get(position).ID;
                        Intent intent = new Intent(getActivity().getApplicationContext(), ArticleDetailActivity.class); //从当前界面跳转到文章详情
                        intent.putExtra("EatingHealthArticleContent", content);
                        intent.putExtra("EatingHealthArticleID",articleID);
                        intent.putExtra("key", 2);
                        startActivity(intent);
                    }
                }
            });
        }
    }
}
